<template>
  <el-dialog
    :title="form.id?'编辑部门': '新增部门'"
    :visible="showDialog"
    width="50%"
    @close="close"
  >
    <el-form
      ref="fm"
      label-width="120px"
      :model="form"
      :rules="rules"
    >
      <el-form-item
        label="部门名称"
        prop="name"
      >
        <el-input
          v-model="form.name"
          style="width:80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门编码"
        prop="code"
      >
        <el-input
          v-model="form.code"
          style="width:80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item
        label="部门负责人"
        prop="manager"
      >
        <el-select
          v-model="form.manager"
          style="width:80%"
          placeholder="请选择"
        >
          <!--
          label 选项显示什么
          value 决定存什么值
         -->
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="部门介绍"
        prop="introduce"
      >
        <el-input
          v-model="form.introduce"
          style="width:80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="$emit('close-dialog', false)">取消</el-button>
      <el-button
        type="primary"
        @click="addDept()"
      >确定</el-button>
    </span>

  </el-dialog>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees.js'
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments.js'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    parentDept: {
      type: Object,
      // default: () => {
      //   return {}
      // }
      // 简写
      default: () => ({})
    },
    allDepts: {
      type: Array,
      default: () => []
    }
  },
  data () {
    /**
     * value 当前校验的表单值
     * cb 控制校验是否通过，cb() 通过  | cb(new Error('错误通知信息'))
     */
    const validCode = (rule, value, cb) => {
      let flag
      if (this.form.id) {
        flag = this.allDepts.some(item => item.code === value && value !== this.parentDept.code)
      } else {
        flag = this.allDepts.some(item => item.code === value)
      }
      if (flag) {
        cb(new Error('部门编码重复'))
      }
      cb()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: ['blur', 'change'] }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: ['blur', 'change'] },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: ['blur', 'change'] },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: ['blur', 'change'] }
        ]
      },
      peoples: []
    }
  },
  created () {
    this.getPeoples()
  },
  methods: {
    close () {
      this.$emit('close-dialog', false)
      // 这里手动清除的目的，是为了实现编辑功能做准备
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      // 清除校验残留
      this.$refs.fm.resetFields()
    },
    async addDept () {
      try {
        await this.$refs.fm.validate()
        if (this.form.id) {
          await updateDepartments(this.form)
        } else {
          await addDepartments({ ...this.form, pid: this.parentDept.id || '' })
        }
        this.$emit('refresh-dept')
        this.$emit('close-dialog', false)
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    async getPeoples () {
      const res = await getEmployeeSimple()
      this.peoples = res
    },
    // 获取编辑部门详情数据
    async getDeptDetil (id) {
      const data = await getDepartDetail(id)
      this.form = data
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
